<template>
<!-- 根据条件从后端返回数据 -->
<el-form ref="big_form" :label-position=" 'right' " label-width="90px"
				 :inline="true">
	<el-form-item prop="use" label="启用状态">
		<el-radio-group v-model="big_use">
      <el-radio-button value="enable">启用</el-radio-button>
      <el-radio-button value="not_enable">未启用</el-radio-button>
      <el-radio-button value="all">全部</el-radio-button>
		</el-radio-group>
	</el-form-item>
	<el-form-item>
		<el-button type="primary" @click="return_big_list()">搜索</el-button>
	</el-form-item>
	<el-form-item>
		<el-button type="primary" @click="return_small_list()">导出表格</el-button>
	</el-form-item>
</el-form>

<!-- 操作面板 -->
<el-form :label-position=" 'right' " label-width="90px" :inline="true">
	<el-form-item>
		<el-button @click=" handleAdd() ">添加大类</el-button>
	</el-form-item>
</el-form>

<!-- 表格数据显示区域 -->
<!-- 这建立在id唯一的情况下 -->
<el-table :data="big_list" style="width: 100%" row-key="id" id="table5_id"
					show-summary>
	<!--选择框-->
	<el-table-column label="编号" prop="id" v-if=" false "/>
	<el-table-column label="大类名称" prop="big_name" sortable/>
	<el-table-column label="助记码前缀" prop="prefix" sortable/>
	<el-table-column label="在库金额" prop="total"/>

	<el-table-column label="是否启用">
		<template #default="scope">
			<el-switch v-model="scope.row.use" size="small" @click="switch_change(scope.row)"/>
		</template>
	</el-table-column>

	<el-table-column align="right">
		<template #header></template>
		<template #default="scope">
			<el-button size="small" @click="jump_to_small(scope.row)">跳转</el-button>
			<el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
			<el-button
				size="small"
				type="danger"
				@click="handleDelete(scope.$index, scope.row)"
			>删除
			</el-button>
		</template>
	</el-table-column>
</el-table>

<el-pagination
	v-model:current-page="currentPage"
	v-model:page-size="pageSize"
	:page-sizes="[100, 200, 500]"
	:small="small"
	:disabled="disabled"
	:background="background"
	layout="total, sizes, prev, pager, next, jumper"
	:total=" total "
/>

<!--添加/修改大类-->
<el-dialog v-model="add_or_update_form_visible"
					 :title=" add_or_update_big_signal "
					 :close-on-click-modal='false'
					 :close-on-press-escape='false'
					 :show-close='false'>

	<el-form :model="add_or_update_big_variable" :rules="add_or_update_big_rules" ref="add_or_update_form_ref" :label-position=" 'right' " label-width="90px">
		<!-- :rules="rules" -->
		<el-form-item prop="big_name" label="大类名称">
			<el-input v-model="add_or_update_big_variable.big_name" autocomplete="off"/>
		</el-form-item>

		<el-form-item prop="prefix" label="大类前缀">
			<el-input v-model="add_or_update_big_variable.prefix" autocomplete="off"/>
		</el-form-item>

	</el-form>
	<template #footer>
      <span class="dialog-footer">
        <el-button @click="add_or_update_form_visible = false">取消</el-button>
        <el-button type="primary" @click="add_or_update_big()">
          保存
        </el-button>
      </span>
	</template>
</el-dialog>
</template>

<script setup lang="ts">
import {reactive, ref, watch} from 'vue'
import type {FormInstance} from 'element-plus'
import {ElMessage, FormRules} from "element-plus";
import {
	BigInfo,
	BigOrSmallStopUseResponse,
	BigTableCRUDResponse
} from "@/api/first/PartsManagement/type.ts";
import {reqBigList, reqBigStopUse} from "@/api/first/PartsManagement";    // 引入新函数
import {make_excel_file} from '@/hooks/make_excel_file.ts'

// const total_index = () => {
//   return ['aaa', 'aaa']
// }

// 跳转到小类表
const emit = defineEmits(['jump'])
const jump_to_small = (row: BigInfo) => {
	emit('jump', row.id)
}

const return_small_list = () => {
	make_excel_file('库存检查表', 'table5_id')
}

// 大类表所需要的变量和函数
const big_form = ref<FormInstance>() // big表检索条件表单的ref

const big_list = ref<BigInfo[]>([]) // big表的数据
const big_use = ref<string>('enable') // 需要传回后端的内容

// 分页
const background = ref<boolean>(true)  // 是否带背景方框
const disabled = ref<boolean>(false)  // 是否可用
const small = ref<boolean>(false)  // 普通大小还是小一号
const currentPage = ref<number>(1)  // 当前所在页数
const pageSize = ref<number>(100)  // 一页有几条记录
const total = ref<number>(0) // 总条数

// 同时监视所在页数和一页有几条记录两者的变化
watch([currentPage, pageSize], () => {
	reqBigList({
		mode: 'read',
		read: {
			use: big_use.value,
			start: (currentPage.value - 1) * pageSize.value,
			stop: currentPage.value * pageSize.value,
		}
	}).then((res: BigTableCRUDResponse) => {
		big_list.value = res.read?.big_list as BigInfo[]
		total.value = res.read?.total as number
		ElMessage.success(res.success?.message)
	})
})

// 添加或修改大类零件
const add_or_update_form_ref = ref<FormInstance>()
const add_or_update_big_signal = ref<string>('')  // 取值为 添加 或者 修改
const add_or_update_form_visible = ref<boolean>(false)  // 控制大类表的添加或删除弹框是否出现


const add_or_update_big_rules = reactive<FormRules>({
	big_name: [{
		type: 'string',
		message: '领用方名称应小于等于20个字符',
		max: 20,
		min: 1,
		required: true
	}],
	prefix: [{
		type: 'string',
		message: '助记码应小于等于20个字符',
		max: 10,
		min: 1,
		required: true
	}],
})

const add_or_update_big_variable = reactive<{
	id: number | '',
	prefix: string,
	big_name: string,
	index: number | null
}>({
	id: '',
	big_name: '',
	prefix: '',
	index: null
})

// 弹出添加框并准备框中的内容
const handleAdd = () => {
	add_or_update_form_visible.value = true
	add_or_update_big_signal.value = '添加大类'
	add_or_update_big_variable.big_name = ''
	add_or_update_big_variable.prefix = ''
	add_or_update_form_ref.value?.clearValidate()
}

// 弹出修改框并准备框中的内容
const handleEdit = (index: number, row: BigInfo) => {
	add_or_update_form_visible.value = true
	add_or_update_big_signal.value = '修改大类'
	add_or_update_big_variable.id = row.id
	add_or_update_big_variable.big_name = row.big_name
	add_or_update_big_variable.prefix = row.prefix
	add_or_update_big_variable.index = index
	add_or_update_form_ref.value?.clearValidate()
}

// 点击添加框中的确认，执行添加
const add_or_update_big = async () => {
	await add_or_update_form_ref.value?.validate()
	add_or_update_form_visible.value = false
	if (add_or_update_big_signal.value === '添加大类') {
		const result: BigTableCRUDResponse = await reqBigList({
			mode: 'create',
			create: {
				big_name: add_or_update_big_variable.big_name,
				prefix: add_or_update_big_variable.prefix
			},
		})
		big_list.value.unshift({
			id: result?.create as number,
			big_name: add_or_update_big_variable.big_name,
			prefix: add_or_update_big_variable.prefix,
			total: 0,
			use: true
		})
		ElMessage.success(result.success?.message)
	} else {
		const result: BigTableCRUDResponse = await reqBigList({
			mode: 'update',
			update: {
				id: add_or_update_big_variable.id as number,
				big_name: add_or_update_big_variable.big_name,
				prefix: add_or_update_big_variable.prefix,
			},
		})
		let temp = big_list.value[add_or_update_big_variable.index as number]
		temp.big_name = add_or_update_big_variable.big_name
		temp.prefix = add_or_update_big_variable.prefix
		ElMessage.success(result.success?.message)
	}
}


const return_big_list = () => {
	reqBigList({
		mode: 'read',
		read: {
			use: big_use.value,
			start: (currentPage.value - 1) * pageSize.value,
			stop: currentPage.value * pageSize.value,
		}
	}).then((res: BigTableCRUDResponse) => {
		big_list.value = res.read?.big_list as BigInfo[]
		total.value = res.read?.total as number
		ElMessage.success(res.success?.message)
	})
}

// 通过switch修改使用情况
const switch_change = async(row: BigInfo) => {
	const result: BigOrSmallStopUseResponse = await reqBigStopUse({
		mode: 'big',
		big: {
			use: row.use,
			id: row.id,
		}
	}).catch(() => {
		// 修改被拒绝，现场恢复原状
		row.use = !row.use
	})
	ElMessage.success(result.success?.message)
}

// 删除
const handleDelete = async (index: number, row: BigInfo) => {
	if(row.use){
		ElMessage.warning('该大类尚未停止使用')
		return
	}
	const result: BigTableCRUDResponse = await reqBigList({
		mode: 'delete',
		delete: {
			id: row.id,
			big_name: row.big_name
		}
	})
	big_list.value.splice(index, 1)
	ElMessage.success(result.success?.message)
}
</script>

<style scoped>

</style>